package com.toycloud.business.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.toycloud.business.domain.DemandConfig;
import com.toycloud.business.domain.DemandRecord;
import com.toycloud.business.domain.bo.DemandPanelBo;
import com.toycloud.business.domain.bo.DemandRecordBo;
import com.toycloud.business.domain.bo.DemandRecordPageBo;
import com.toycloud.business.domain.vo.DemandRecordVo;
import com.toycloud.business.domain.vo.PanelDto;
import com.toycloud.business.dto.results.CommonResult;
import com.toycloud.business.dto.results.UserParam;
import com.toycloud.business.service.IDemandRecordService;
import com.toycloud.common.core.domain.PageQuery;
import com.toycloud.common.core.page.TableDataInfo;
import com.toycloud.common.core.utils.DateUtils;
import com.toycloud.common.math.PercentFormat;
import com.toycloud.common.sso.api.RemoteSsoService;
import com.toycloud.common.utils.BeanCopyUtils;
import com.toycloud.common.utils.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.toycloud.system.domain.feedback.FeedbackConfig;
import com.toycloud.system.mapper.business.FeedbackApplicationVersionManagerDetailMapper;
import com.toycloud.system.mapper.demand.DemandConfigMapper;
import com.toycloud.system.mapper.demand.DemandRecordMapper;
import com.toycloud.system.mapper.feedback.FeedbackConfigMapper;
import com.toycloud.system.service.business.IFeedbackApplicationVersionManagerDetailService;
import com.toycloud.system.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.IntStream;

/**
 * demandService业务层处理
 *
 * @author binlu6
 * @date 2024-10-31
 */
@RequiredArgsConstructor
@Service
public class DemandRecordServiceImpl implements IDemandRecordService {

    private final DemandRecordMapper baseMapper;

    private final DemandConfigMapper configMapper;

    private final FeedbackConfigMapper feedbackConfigMapper;

    @Resource
    FeedbackApplicationVersionManagerDetailMapper feedbackApplicationVersionManagerDetailMapper;

    @Resource
    @Lazy
    IFeedbackApplicationVersionManagerDetailService iFeedbackApplicationVersionManagerDetailService;

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RemoteSsoService remoteSsoService;

    public static final String APPID = "wdiON2lqQGqMjBHA70Rce";

    private final HashMap<Integer,String> statusMap =new HashMap<>();

    /**
     * 查询demand
     */
    @Override
    public DemandRecordVo queryById(Integer id){
        DemandRecordVo vo =baseMapper.selectVoById(id);
//        if(vo.getDemandResource()!=null&& !vo.getDemandResource().equals("[]")){
//            List<String> label = vo.getDemandResource();
//            List<String> labelName =new ArrayList<>();
//            if(!label.isEmpty()) {
//                label.forEach(i -> {
//                    DemandConfig demandConfig = configMapper.selectByPrimaryKey(Long.valueOf(i));
//                    if (demandConfig != null) {
//                        labelName.add(demandConfig.getName());
//                    }
//                });
//            }
//            vo.setDemandResource(labelName);
//        }
        if(vo.getApplicationLabel()!=null&& !vo.getApplicationLabel().equals("[]")){
            List<String> label = vo.getApplicationLabel();
            List<String> labelName =new ArrayList<>();
            List<String> applicationVersion = new ArrayList<>();
            if(!label.isEmpty()) {
                label.forEach(i -> {
                    DemandConfig demandConfig = configMapper.selectByPrimaryKey(Long.valueOf(i));
                    if (demandConfig != null) {
                        labelName.add(demandConfig.getName());
                        applicationVersion.add(demandConfig.getName()+vo.getDemandVersion());
                    }
                });
            }
            vo.setApplicationLabelName(labelName);
//            vo.setApplicationVersion(applicationVersion);
        }
        // 版本管理应用标签和版本管理应用版本
        if (vo.getAppApply() != null && !vo.getAppApply().equals("[]")) {
            List<String> label = vo.getAppApply();
            List<String> version = vo.getAppVersion();
            List<String> labelName = new ArrayList<>();
            List<String> applicationVersion = new ArrayList<>();

            if (!label.isEmpty()) {
                // 使用索引遍历保证位置对应
                IntStream.range(0, label.size()).forEach(index -> {
                    DemandConfig demandConfig = configMapper.selectByPrimaryKey(Long.valueOf(label.get(index)));
                    if (demandConfig != null) {
                        // 获取当前标签名
                        String currentLabel = demandConfig.getName();
                        labelName.add(currentLabel);

                        // 检查版本是否存在且长度足够
                        if (version != null && version.size() > index) {
                            String combined = currentLabel + version.get(index);
                            applicationVersion.add(combined);
                        } else {
                            // 如果版本不存在或长度不足，仅添加标签名
                            applicationVersion.add(currentLabel);
                        }
                    }
                });
            }
            vo.setApplicationVersion(applicationVersion);
        }

        if(vo.getCategoryLabel()!=null&& !vo.getCategoryLabel().equals("[]")){
            List<String> category = vo.getCategoryLabel();
            List<String> categoryName =new ArrayList<>();
            if(!category.isEmpty()) {
                category.forEach(i -> {
//                    DemandConfig demandConfig = configMapper.selectByPrimaryKey(Long.valueOf(i));
                    FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(i));
                    if (feedbackConfig != null) {
                        categoryName.add(feedbackConfig.getName());
                    }
                });
            }
            vo.setCategoryLabelName(categoryName);
        }
        if(vo.getModelLabel()!=null&& !vo.getModelLabel().equals("[]")){
            List<String> modelLabel = vo.getModelLabel();
            List<String> modelname =new ArrayList<>();
            if(!modelLabel.isEmpty()) {
                modelLabel.forEach(i -> {
                    FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(i));
                    if (feedbackConfig != null) {
                        modelname.add(feedbackConfig.getName());
                    }
                });
            }
            vo.setModelLabelName(modelname);
        }
//        vo.setProductLabelList(vo.getProductLabel());
//        if(vo.getProductLabel()!=null&& !vo.getProductLabel().equals("[]")){
//            List<String> product = vo.getProductLabel();
//            List<String> productName =new ArrayList<>();
//            if(!product.isEmpty()) {
//                product.forEach(i -> {
//                    FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(i));
//                    if (feedbackConfig != null) {
//                        productName.add(feedbackConfig.getName());
//                    }
//                });
//            }
//            vo.setProductLabelName(productName);
//        }

        if(vo.getVersionCategory()!=null&& !vo.getVersionCategory().equals("[]")){
            List<String> category = vo.getVersionCategory();
            List<String> categoryName =new ArrayList<>();
            if(!category.isEmpty()) {
                category.forEach(i -> {
                    FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(i));
                    if (feedbackConfig != null) {
                        categoryName.add(feedbackConfig.getName());
                    }
                });
            }
            vo.setVersionCategoryName(categoryName);
        }
        if(vo.getVersionModel()!=null&& !vo.getVersionModel().equals("[]")){
            List<String> modelLabel = vo.getVersionModel();
            List<String> modelname =new ArrayList<>();
            if(!modelLabel.isEmpty()) {
                modelLabel.forEach(i -> {
                    FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(i));
                    if (feedbackConfig != null) {
                        modelname.add(feedbackConfig.getName());
                    }
                });
            }
            vo.setVersionModelName(modelname);
        }

        List<String> labelName =vo.getVersionCategoryName();
        List<String> modelName = vo.getVersionModelName();
        List<String> versionName = vo.getVersionModelVersion();
        // 新建一个列表 list2
        List<String> list2 = new ArrayList<>();
        if(labelName!=null&&!labelName.isEmpty()){
            if (labelName != null && !labelName.isEmpty() &&
                    modelName != null && !modelName.isEmpty() &&
                    versionName != null && !versionName.isEmpty()) {
                // 确保三个列表的大小相同
                int size = Math.min(labelName.size(), Math.min(modelName.size(), versionName.size()));
                for (int j = 0; j < size; j++) {
                    String combined = labelName.get(j) + modelName.get(j) + versionName.get(j);
                    list2.add(combined);
                }
            }
            vo.setCategoryModelVersion(list2);
        }

        return vo;
    }

    @Override
    public Integer changeById(Integer id) {
        boolean flag =baseMapper.updateByPrimaryKey(id)>0;
        DemandRecordVo changeVo = baseMapper.selectVoById(id);
        DemandRecordBo bo = new DemandRecordBo();
        bo.setDemandVersion(StringUtils.incrementVersion(changeVo.getDemandVersion()));
        bo.setDemandId(changeVo.getId());
        bo.setDemandContent(changeVo.getDemandContent());
        bo.setEnterFile(changeVo.getEnterFile());
        bo.setDemandResource(changeVo.getDemandResource());
        bo.setDemandPerson(changeVo.getDemandPerson());
        bo.setProposeTime(changeVo.getProposeTime());
        bo.setApplicationLabel(changeVo.getApplicationLabel());
        bo.setCategoryLabel(changeVo.getCategoryLabel());
        bo.setModelLabel(changeVo.getModelLabel());
        bo.setFilterStatus("0");
        Integer newDemandId =this.copyByBo(bo);
        return newDemandId;
    }


    public Integer copyByBo(DemandRecordBo bo) {
        DemandRecord add = BeanUtil.toBean(bo, DemandRecord.class);
        add.setNowStatus("1");
        if(bo.getFilterStatus().equals("1")){
            add.setNowStatus("2");
            if(bo.getSurveyStatus().equals("1")){
                add.setNowStatus("3");
                if(bo.getAnalysisStatus().equals("1")){
                    add.setNowStatus("4");
                    if(bo.getReviewStatus().equals("1")){
                        add.setNowStatus("5");
                        if(bo.getDesignStatus().equals("1")){
                            add.setNowStatus("6");
                            if(bo.getDevelopStatus().equals("1")){
                                add.setNowStatus("7");
                                if(bo.getReleaseStatus().equals("1")){
                                    add.setNowStatus("8");
                                }
                            }
                        }
                    }
                }
            }
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        add.setCreateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        Integer id =null;
        if(flag){
            id =add.getId();
        }

        return id;
    }

    public List<DemandRecordVo> setVoList(List<DemandRecordVo> list){
        list.forEach(i->{
            // 查询model标签
            if(i.getModelLabel()!=null && !i.getModelLabel().isEmpty()){
                List<String> label = i.getModelLabel();
                List<String> labelName =new ArrayList<>();
                if(!label.isEmpty()) {
                    label.forEach(x -> {
                        FeedbackConfig feedbackConfig= feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(x.toString()));
                        if (feedbackConfig != null) {
                            labelName.add(feedbackConfig.getName());
                        }
                    });
                }
                i.setModelLabelName(labelName);
            }else{
                i.setModelLabelName(new ArrayList<>());
            }
            // 查询需求来源
            if(i.getDemandResource()!=null && !i.getDemandResource().isEmpty()){
                List<String> label = i.getDemandResource();
                List<String> labelName =new ArrayList<>();
                if(!label.isEmpty()) {
                    label.forEach(x -> {
                        DemandConfig demandConfig= configMapper.selectByPrimaryKey(Long.valueOf(x.toString()));
                        if (demandConfig != null) {
                            labelName.add(demandConfig.getName());
                        }
                    });
                }
                i.setDemandResourceName(labelName);
            }else{
                i.setDemandResourceName(new ArrayList<>());
            }
            // 查询需求端
            if(i.getAnalysisSide()!=null && !i.getAnalysisSide().isEmpty()){
                List<String> label = i.getAnalysisSide();
                List<String> labelName =new ArrayList<>();
                if(!label.isEmpty()) {
                    label.forEach(x -> {
                        DemandConfig demandConfig= configMapper.selectByPrimaryKey(Long.valueOf(x.toString()));
                        if (demandConfig != null) {
                            labelName.add(demandConfig.getName());
                        }
                    });
                }
                i.setAnalysisSideName(labelName);
            }else{
                i.setAnalysisSideName(new ArrayList<>());
            }
            // 查询涉及部门
            if(i.getAnalysisDep()!=null && !i.getAnalysisDep().isEmpty()){
                List<String> label = i.getAnalysisDep();
                List<String> labelName =new ArrayList<>();
                if(!label.isEmpty()) {
                    label.forEach(x -> {
                        DemandConfig demandConfig= configMapper.selectByPrimaryKey(Long.valueOf(x.toString()));
                        if (demandConfig != null) {
                            labelName.add(demandConfig.getName());
                        }
                    });
                }
                i.setAnalysisDepName(labelName);
            }else{
                i.setAnalysisDepName(new ArrayList<>());
            }
            // 查询需求类型
            if(i.getDemandType()!=null && !i.getDemandType().isEmpty()){
                List<String> label = i.getDemandType();
                i.setDemandTypeName(label.get(0));
            }else{
                i.setDemandTypeName("");
            }
            // 查询应用标签
//            i.setApplicationLabelList(i.getApplicationLabel());
            if(i.getApplicationLabel()!=null&&!i.getApplicationLabel().equals("[]")){
                List<String> labelName =new ArrayList<>();
                List<String> label = i.getApplicationLabel();
                List<String> applicationVersion = new ArrayList<>();
                if(!label.isEmpty()){
                    label.forEach(x->{
                        DemandConfig demandConfig =configMapper.selectByPrimaryKey(Long.valueOf(x.toString()));
                        if(demandConfig!=null) {
                            labelName.add(demandConfig.getName());
                            applicationVersion.add(demandConfig.getName()+i.getDemandVersion());
                        }
                    });
                }
//                i.setApplicationVersion(applicationVersion);
                i.setApplicationLabelName(labelName);
            }else{
                i.setApplicationLabelName(new ArrayList<>());
            }
            // 版本管理应用标签和版本管理应用版本
            if (i.getAppApply() != null && !i.getAppApply().equals("[]")) {
                List<String> label = i.getAppApply();
                List<String> version = i.getAppVersion();
                List<String> labelName = new ArrayList<>();
                List<String> applicationVersion = new ArrayList<>();

                if (!label.isEmpty()) {
                    // 使用索引遍历保证位置对应
                    IntStream.range(0, label.size()).forEach(index -> {
                        DemandConfig demandConfig = configMapper.selectByPrimaryKey(Long.valueOf(label.get(index)));
                        if (demandConfig != null) {
                            // 获取当前标签名
                            String currentLabel = demandConfig.getName();
                            labelName.add(currentLabel);

                            // 检查版本是否存在且长度足够
                            if (version != null && version.size() > index) {
                                String combined = currentLabel + version.get(index);
                                applicationVersion.add(combined);
                            } else {
                                // 如果版本不存在或长度不足，仅添加标签名
                                applicationVersion.add(currentLabel);
                            }
                        }
                    });
                }
                i.setApplicationVersion(applicationVersion);
            }
            // 查询品类标签
            if(i.getCategoryLabel()!=null && !i.getCategoryLabel().equals("[]")){
                List<String> label = i.getCategoryLabel();
                List<String> labelName =new ArrayList<>();
                if(!label.isEmpty()) {
                    label.forEach(x -> {
                        FeedbackConfig demandConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(x.toString()));
                        if (demandConfig != null) {
                            labelName.add(demandConfig.getName());
                        }
                    });
                }
                i.setCategoryLabelName(labelName);
            }else{
                i.setCategoryLabelName(new ArrayList<>());
            }
            // 查询产品标签
//            if(i.getProductLabel()!=null && !i.getProductLabel().equals("[]")){
//                List<String> label = i.getProductLabel();
//                List<String> labelName =new ArrayList<>();
//                if(!label.isEmpty()) {
//                    label.forEach(x -> {
//                        FeedbackConfig demandConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(x));
//                        if (demandConfig != null) {
//                            labelName.add(demandConfig.getName());
//                        }
//                    });
//                }
//                i.setProductLabelName(labelName);
//            }else{
//                i.setProductLabelName(new ArrayList<>());
//            }

            if(i.getVersionCategory()!=null&& !i.getVersionCategory().equals("[]")){
                List<String> category = i.getVersionCategory();
                List<String> categoryName =new ArrayList<>();
                if(!category.isEmpty()) {
                    category.forEach(x -> {
                        FeedbackConfig demandConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(x.toString()));
                        if (demandConfig != null) {
                            categoryName.add(demandConfig.getName());
                        }
                    });
                }
                i.setVersionCategoryName(categoryName);
            }
            if(i.getVersionModel()!=null&& !i.getVersionModel().equals("[]")){
                List<String> modelLabel = i.getVersionModel();
                List<String> modelname =new ArrayList<>();
                if(!modelLabel.isEmpty()) {
                    modelLabel.forEach(x -> {
                        FeedbackConfig feedbackConfig = feedbackConfigMapper.selectByPrimaryKey(Long.valueOf(x));
                        if (feedbackConfig != null) {
                            modelname.add(feedbackConfig.getName());
                        }
                    });
                }
                i.setVersionModelName(modelname);
            }
            List<String> labelName =i.getVersionCategoryName();
            List<String> modelName = i.getVersionModelName();
            List<String> versionName = i.getVersionModelVersion();
            // 新建一个列表 list2
            List<String> list2 = new ArrayList<>();
            if(labelName!=null&&!labelName.isEmpty()){
                if (labelName != null && !labelName.isEmpty() &&
                        modelName != null && !modelName.isEmpty() &&
                        versionName != null && !versionName.isEmpty()) {
                    // 确保三个列表的大小相同
                    int size = Math.min(labelName.size(), Math.min(modelName.size(), versionName.size()));
                    for (int j = 0; j < size; j++) {
                        String combined = labelName.get(j) + modelName.get(j) + versionName.get(j);
                        list2.add(combined);
                    }
                }
                i.setCategoryModelVersion(list2);
            }
            i.setanalysisRelyName(i.getAnalysisRely());
        });
        return list;
    }

    /**
     * 查询demand列表
     */
    @Override
    public TableDataInfo<DemandRecordVo> queryPageList(DemandRecordPageBo bo) {
        DemandRecordBo pageBo  = new DemandRecordBo();
        if("1".equals(bo.getType())){
           bo.setId(null);
        }
        BeanCopyUtils.copy(bo,pageBo);
        PageQuery pageQuery =new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        LambdaQueryWrapper<DemandRecord> lqw = buildQueryWrapper(pageBo);
        if("1".equals(bo.getType())){
            List<String> demandids =feedbackApplicationVersionManagerDetailMapper.getAppidsByParentid(bo.getAppid());
            if(demandids.size()!=0){
                lqw.in(DemandRecord::getId,demandids);
            }
        }
        Page<DemandRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<DemandRecordVo> list =this.setVoList(result.getRecords());

        // 上一个 下一个
        DemandRecordVo resultVo = null;
        int i = 0;
        long prevId = 0;
        long nextId = 0;
        for(DemandRecordVo demandRecordVo :list){
            if (i == 0) {
                prevId = 0;
            } else {
                prevId = list.get(i - 1).getId();
            }

            if (i == list.size() - 1) {
                nextId = 0;
            } else {
                nextId = list.get(i + 1).getId();
            }
            i++;
           demandRecordVo.setPrevId(prevId);
           demandRecordVo.setNextId(nextId);
        }
        result.setRecords(list);
        return TableDataInfo.build(result);
    }

    @Override
    public List<PanelDto> queryPanel(String categoryType) {
        //        （0enter, 1filter,2survey,3analysis,4.review，5design,6develop,7release,8上市）
        statusMap.put(0,"需求录入");
        statusMap.put(1,"需求筛选");
        statusMap.put(2,"需求调研");
        statusMap.put(3,"需求分析");
        statusMap.put(4,"需求评审");
        statusMap.put(5,"产品设计");
        statusMap.put(6,"产品开发");
        statusMap.put(7,"产品发布");
        statusMap.put(8,"上市验证");
        List<PanelDto> list;
        PanelDto enterDto = new PanelDto();
        PanelDto newFilter = new PanelDto();
        // 全部包含
        if(categoryType.equals("all")){
            list = baseMapper.queryPanelList(null);
            list.forEach(x->{
                DemandRecordBo newBo = new DemandRecordBo();
                newBo.setCategoryLabel(new ArrayList<>());
//                BeanCopyUtils.copy(categoryType,newBo);
                newBo.setNowStatus(x.getStatusValue());
                Integer All =baseMapper.queryStage(newBo);
                x.setAll(All);
                x.setStatusValue(statusMap.get(x.getStatusType()));
                String percentage =PercentFormat.formatPercent(x.getAll()-x.getCount(),x.getAll());
                x.setCalc(percentage);
                if("需求录入".equals(x.getStatusValue())){
                    BeanCopyUtils.copy(x,enterDto);
                }
                if("需求筛选".equals(x.getStatusValue())){
                    BeanCopyUtils.copy(x,newFilter);
                    newFilter.setCount(newFilter.getCount());
                    newFilter.setAll( newFilter.getAll());
                    newFilter.setCalc(PercentFormat.formatPercent(newFilter.getCount(),newFilter.getAll()));
                    newFilter.setStatusValue("需求筛选");
                    newFilter.setStatusType(1);
                    BeanCopyUtils.copy(newFilter,x);
                }
            });
        }else{
            list = baseMapper.queryPanelList(Collections.singletonList(categoryType));
            list.forEach(x->{
                DemandRecordBo newBo = new DemandRecordBo();
                newBo.setCategoryLabel(Collections.singletonList(categoryType));
//                BeanCopyUtils.copy(categoryType,newBo);
                newBo.setNowStatus(x.getStatusValue());
                Integer All =baseMapper.queryStage(newBo);
                x.setAll(All);
                x.setStatusValue(statusMap.get(x.getStatusType()));
                String percentage =PercentFormat.formatPercent(x.getAll()-x.getCount(),x.getAll());
                x.setCalc(percentage);
                if("需求录入".equals(x.getStatusValue())){
                    BeanCopyUtils.copy(x,enterDto);
                }
                if("需求筛选".equals(x.getStatusValue())){
                    BeanCopyUtils.copy(x,newFilter);
                    newFilter.setCount(newFilter.getCount());
                    newFilter.setAll(newFilter.getAll());
                    newFilter.setCalc(PercentFormat.formatPercent(newFilter.getCount(),newFilter.getAll()));
                    newFilter.setStatusValue("需求筛选");
                    newFilter.setStatusType(1);
                    BeanCopyUtils.copy(newFilter,x);
                }
            });
        }
        list.removeIf(y -> "需求录入".equals(y.getStatusValue()));
        return list;
    }

    @Override
    public List<PanelDto> queryPanelBybo(DemandPanelBo bo) {
        //        （0enter, 1filter,2survey,3analysis,4.review，5design,6develop,7release,8上市）
        statusMap.put(0,"需求录入");
        statusMap.put(1,"需求筛选");
        statusMap.put(2,"需求调研");
        statusMap.put(3,"需求分析");
        statusMap.put(4,"需求评审");
        statusMap.put(5,"产品设计");
        statusMap.put(6,"产品开发");
        statusMap.put(7,"产品发布");
        statusMap.put(8,"上市验证");
        // 品类查询
        List<PanelDto> categorylist;
        // 型号查询
        List<PanelDto> modelList;
        PanelDto enterDto = new PanelDto();
        PanelDto newFilter = new PanelDto();
        if(!bo.getModelList().isEmpty()){
            // 型号处理
            modelList = baseMapper.queryPanelListByModel(bo.getModelList());
            modelList.forEach(x->{
                DemandRecordBo newBo = new DemandRecordBo();
                newBo.setModelLabel(bo.getModelList());
                newBo.setNowStatus(x.getStatusValue());
                Integer All =baseMapper.queryStageByModel(newBo);
                x.setAll(All);
                x.setStatusValue(statusMap.get(x.getStatusType()));
                String percentage =PercentFormat.formatPercent(x.getAll()-x.getCount(),x.getAll());
                x.setCalc(percentage);
                if("需求录入".equals(x.getStatusValue())){
                    BeanCopyUtils.copy(x,enterDto);
                }
                if("需求筛选".equals(x.getStatusValue())){
                    BeanCopyUtils.copy(x,newFilter);
                    newFilter.setCount(newFilter.getCount());
                    newFilter.setAll(newFilter.getAll());
                    newFilter.setCalc(PercentFormat.formatPercent(newFilter.getAll()-newFilter.getCount(),newFilter.getAll()));
                    newFilter.setStatusValue("需求筛选");
                    newFilter.setStatusType(1);
                    BeanCopyUtils.copy(newFilter,x);
                }
            });
            modelList.removeIf(y -> "需求录入".equals(y.getStatusValue()));
            return modelList;
        }else {
            // 类别处理
            categorylist = baseMapper.queryPanelList(bo.getCategoryList());
            categorylist.forEach(x->{
                DemandRecordBo newBo = new DemandRecordBo();
                newBo.setCategoryLabel(bo.getCategoryList());
                newBo.setNowStatus(x.getStatusValue());
                Integer All =baseMapper.queryStage(newBo);
                x.setAll(All);
                x.setStatusValue(statusMap.get(x.getStatusType()));
                String percentage =PercentFormat.formatPercent(x.getAll()-x.getCount(),x.getAll());
                x.setCalc(percentage);
                if("需求录入".equals(x.getStatusValue())){
                    BeanCopyUtils.copy(x,enterDto);
                }
                if("需求筛选".equals(x.getStatusValue())){
                    BeanCopyUtils.copy(x,newFilter);
                    newFilter.setCount(newFilter.getCount());
                    newFilter.setAll(newFilter.getAll());
                    newFilter.setCalc(PercentFormat.formatPercent(newFilter.getAll()-newFilter.getCount(),newFilter.getAll()));
                    newFilter.setStatusValue("需求筛选");
                    newFilter.setStatusType(1);
                    BeanCopyUtils.copy(newFilter,x);
                }
            });
            categorylist.removeIf(y -> "需求录入".equals(y.getStatusValue()));
            return categorylist;
        }
    }


    /**
     * 查询demand列表
     */
    @Override
    public List<DemandRecordVo> queryList(DemandRecordBo bo) {
        LambdaQueryWrapper<DemandRecord> lqw = buildQueryWrapper(bo);
        List<DemandRecordVo> list = baseMapper.selectVoList(lqw);
        List<DemandRecordVo> newlist =this.setVoList(list);
        return newlist;
    }

    private LambdaQueryWrapper<DemandRecord> buildQueryWrapper(DemandRecordBo bo) {
        Map<String, Object> params = bo.getParams();

        // 获取 productLabel 数组
        List<String> AnalysisSelect = bo.getAnalysisSelect();
        // 获取 demandResource 数组
        List<String> demandResource = bo.getDemandResource();
        // 获取 demandType 数组
        List<String> demandType = bo.getDemandType();

        // 获取 demandResource 数组
        List<String> analysisSide = bo.getAnalysisSide();

        // 获取 demandResource 数组
        List<String> analysisDep = bo.getAnalysisDep();

        // 获取 applicationLabel 数组
        List<String> applicationLabel = bo.getApplicationLabel();
        // 获取 categoryLabel数组
        List<String> CategoryLabel= bo.getCategoryLabel();
        // 获取 ModelLabel数组
        List<String> ModelLabel =bo.getModelLabel();
        // 获取 版本管理应用标签
        List<String> appApply = bo.getAppApply();
        // 获取 版本管理应用版本
        List<String> appVersion = bo.getAppVersion();
        // 获取 版本管理应用品类
//        List<String> versionCategory = bo.getVersionCategory();
//        // 获取 版本管理应用产品
//        List<String> versionModel = bo.getVersionModel();
//        // 获取 版本管理应用产品版本
//        List<String> versionModelVersion = bo.getVersionModelVersion();
        // 获取 ModelLabel数组
        LambdaQueryWrapper<DemandRecord> lqw = Wrappers.lambdaQuery();
        List<JSONObject> AnalysisRely =bo.getAnalysisRely();

// 用于存放提取的 label 字段值
        List<String> labelValues = new ArrayList<>();

// 提取每个 JsonObject 中的 label 字段值
        if(AnalysisRely!=null&&!AnalysisRely.isEmpty()) {
            for (JSONObject jsonObject : AnalysisRely) {
                String label = jsonObject.getString("id");
                if (StringUtils.isNotBlank(label)) {
                    labelValues.add(label);
                }
            }
            // 根据提取的 labelValues 构造查询
            if (!labelValues.isEmpty()) {
                lqw.and(wrapper -> {
                    for (String label : labelValues) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getAnalysisRely, label);
                    }
                });
            }
        }
        List<String> developStatusArr = bo.getDevelopStatusArr();
        if (developStatusArr != null && developStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : developStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getDevelopStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getDevelopStatus()), DemandRecord::getDevelopStatus, bo.getDevelopStatus());
        lqw.between(params.get("beginDevelopUpdateTime") != null && params.get("endDevelopUpdateTime") != null,
            DemandRecord::getDevelopUpdateTime ,params.get("beginDevelopUpdateTime"), params.get("endDevelopUpdateTime"));
        lqw.eq(bo.getId() != null, DemandRecord::getId, bo.getId());
        lqw.eq(bo.getDemandId() != null, DemandRecord::getDemandId, bo.getDemandId());
        lqw.like(StringUtils.isNotBlank(bo.getDemandVersion()), DemandRecord::getDemandVersion, bo.getDemandVersion());
        lqw.like(StringUtils.isNotBlank(bo.getDemandContent()), DemandRecord::getDemandContent, bo.getDemandContent());
        lqw.like(StringUtils.isNotBlank(bo.getDemandTitle()), DemandRecord::getDemandTitle, bo.getDemandTitle());
        if (demandResource != null && demandResource.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : demandResource) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getDemandResource, label);
                    }
                }
            });
        }
        if (demandType != null && demandType.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : demandType) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getDemandType, label);
                    }
                }
            });
        }
        if (analysisSide != null && analysisSide.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : analysisSide) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getAnalysisSide, label);
                    }
                }
            });
        }
        if (analysisDep != null && analysisDep.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : analysisDep) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getAnalysisDep, label);
                    }
                }
            });
        }
//        lqw.like(StringUtils.isNotBlank((CharSequence) bo.getDemandResource()), DemandRecord::getDemandResource, bo.getDemandResource());
        lqw.like(StringUtils.isNotBlank(bo.getDemandPerson()), DemandRecord::getDemandPerson, bo.getDemandPerson());
        lqw.between(params.get("beginProposeTime") != null && params.get("endProposeTime") != null,
            DemandRecord::getProposeTime ,params.get("beginProposeTime"), params.get("endProposeTime"));
        if (applicationLabel != null && applicationLabel.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : applicationLabel) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getApplicationLabel, label);
                    }
                }
            });
        }
//        lqw.like(StringUtils.isNotBlank((CharSequence) bo.getApplicationLabel()), DemandRecord::getApplicationLabel, bo.getApplicationLabel());

        if (CategoryLabel != null && CategoryLabel.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : CategoryLabel) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getCategoryLabel, label);
                    }
                }
            });
        }
//        lqw.like(StringUtils.isNotBlank((CharSequence) bo.getCategoryLabel()), DemandRecord::getCategoryLabel, bo.getCategoryLabel());
        if (ModelLabel != null && ModelLabel.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : ModelLabel) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getModelLabel, label);
                    }
                }
            });
        }
        if (appApply != null && appApply.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : appApply) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getAppApply, label);
                    }
                }
            });
        }
        if (appVersion != null && appVersion.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : appVersion) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getAppVersion, label);
                    }
                }
            });
        }
        // 查询品类-产品-型号
        List<List<String>> searchCriteria = bo.getSearchCriteria();// 例如: [["939", "49", "v1.0"], ["939", "73", "v1.0"]]
        if (searchCriteria != null && !searchCriteria.isEmpty()) {
            lqw.and(wrapper -> {
                for (List<String> criteria : searchCriteria) {
                    // 将数组转为字符串
                    String a = JSONArray.toJSONString(criteria);
                    if (criteria != null && !criteria.isEmpty()) { // 检查子列表是否为空
                        wrapper.or(subWrapper -> {
                                    subWrapper.like(DemandRecord::getCategoryModelVersion,  a );

                        });
                    }
                }
            });
        }
        // 查询品应用-版本
        List<List<String>> applyVersion = bo.getApplyVersion();// 例如: [["10", "v1.0"], ["6", "v1.0.0"]]
        if (applyVersion != null && !applyVersion.isEmpty()) {
            lqw.and(wrapper -> {
                for (List<String> criteria : applyVersion) {
                    // 将数组转为字符串
                    String a = JSONArray.toJSONString(criteria);
                    if (criteria != null && !criteria.isEmpty()) { // 检查子列表是否为空
                        wrapper.or(subWrapper -> {
                            subWrapper.like(DemandRecord::getApplyVersion,  a );

                        });
                    }
                }
            });
        }

//        lqw.like(StringUtils.isNotBlank((CharSequence) bo.getModelLabel()), DemandRecord::getModelLabel, bo.getModelLabel());

//        lqw.like(StringUtils.isNotBlank((CharSequence) bo.getAnalysisRely()), DemandRecord::getAnalysisRely, bo.getAnalysisRely());
        List<String> enterStatusArr = bo.getEnterStatusArr();
        if (enterStatusArr != null && enterStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : enterStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getEnterStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getEnterStatus()), DemandRecord::getEnterStatus, bo.getEnterStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getFilterLevel()), DemandRecord::getFilterLevel, bo.getFilterLevel());
        List<String> filterStatusArr = bo.getFilterStatusArr();
        if (filterStatusArr != null && filterStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : filterStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getFilterStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getFilterStatus()), DemandRecord::getFilterStatus, bo.getFilterStatus());
        lqw.between(params.get("beginFilterUpdateTime") != null && params.get("endFilterUpdateTime") != null,
            DemandRecord::getFilterUpdateTime ,params.get("beginFilterUpdateTime"), params.get("endFilterUpdateTime"));
        lqw.like(StringUtils.isNotBlank(bo.getSurveyPerson()), DemandRecord::getSurveyPerson, bo.getSurveyPerson());
        lqw.like(StringUtils.isNotBlank(bo.getSceneLabel()), DemandRecord::getSceneLabel, bo.getSceneLabel());
        lqw.like(StringUtils.isNotBlank(bo.getSceneDescribe()), DemandRecord::getSceneDescribe, bo.getSceneDescribe());
        lqw.like(StringUtils.isNotBlank(bo.getDemandValue()), DemandRecord::getDemandValue, bo.getDemandValue());
        lqw.like(StringUtils.isNotBlank(bo.getUserScope()), DemandRecord::getUserScope, bo.getUserScope());
        lqw.like(StringUtils.isNotBlank(bo.getExistingSolution()), DemandRecord::getExistingSolution, bo.getExistingSolution());
        lqw.like(StringUtils.isNotBlank(bo.getExpectedSolution()), DemandRecord::getExpectedSolution, bo.getExpectedSolution());
        lqw.like(StringUtils.isNotBlank(bo.getSurveyRemark()), DemandRecord::getSurveyRemark, bo.getSurveyRemark());
        List<String> surveyStatusArr = bo.getSurveyStatusArr();
        if (surveyStatusArr != null && surveyStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : surveyStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getSurveyStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getSurveyStatus()), DemandRecord::getSurveyStatus, bo.getSurveyStatus());
        lqw.between(params.get("beginSurveyUpdateTime") != null && params.get("endSurveyUpdateTime") != null,
            DemandRecord::getSurveyUpdateTime ,params.get("beginSurveyUpdateTime"), params.get("endSurveyUpdateTime"));
        lqw.like(StringUtils.isNotBlank(bo.getAnalysisPerson()), DemandRecord::getAnalysisPerson, bo.getAnalysisPerson());
        lqw.like(StringUtils.isNotBlank(bo.getAnalysisRoi()), DemandRecord::getAnalysisRoi, bo.getAnalysisRoi());
        lqw.between(params.get("beginAnalysisUpdateTime") != null && params.get("endAnalysisUpdateTime") != null,
            DemandRecord::getAnalysisUpdateTime ,params.get("beginAnalysisUpdateTime"), params.get("endAnalysisUpdateTime"));
        List<String> analysisStatusArr = bo.getAnalysisStatusArr();
        if (analysisStatusArr != null && analysisStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : analysisStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getAnalysisStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getAnalysisStatus()), DemandRecord::getAnalysisStatus, bo.getAnalysisStatus());
        lqw.like(StringUtils.isNotBlank(bo.getReviewPerson()), DemandRecord::getReviewPerson, bo.getReviewPerson());
        lqw.like(StringUtils.isNotBlank(bo.getReviewSum()), DemandRecord::getReviewSum, bo.getReviewSum());
        List<String> reviewStatusArr = bo.getReviewStatusArr();
        if (reviewStatusArr != null && reviewStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : reviewStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getReviewStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getReviewStatus()), DemandRecord::getReviewStatus, bo.getReviewStatus());
        lqw.like(bo.getReviewUpdateTime() != null, DemandRecord::getReviewUpdateTime, bo.getReviewUpdateTime());
        lqw.like(StringUtils.isNotBlank(bo.getDesignPerson()), DemandRecord::getDesignPerson, bo.getDesignPerson());
        lqw.like(StringUtils.isNotBlank(bo.getProductDeliver()), DemandRecord::getProductDeliver, bo.getProductDeliver());
        lqw.like(StringUtils.isNotBlank(bo.getDesignDeliver()), DemandRecord::getDesignDeliver, bo.getDesignDeliver());
        lqw.like(StringUtils.isNotBlank(bo.getUiDeliver()), DemandRecord::getUiDeliver, bo.getUiDeliver());
        lqw.like(StringUtils.isNotBlank(bo.getResourceDeliver()), DemandRecord::getResourceDeliver, bo.getResourceDeliver());
        lqw.like(StringUtils.isNotBlank(bo.getDesignRemark()), DemandRecord::getDesignRemark, bo.getDesignRemark());
        lqw.like(StringUtils.isNotBlank(bo.getDevelopPerson()), DemandRecord::getDevelopPerson, bo.getDevelopPerson());
        lqw.like(StringUtils.isNotBlank(bo.getDevelopSum()), DemandRecord::getDevelopSum, bo.getDevelopSum());
        List<String> designStatusArr = bo.getDesignStatusArr();
        if (designStatusArr != null && designStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : designStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getDesignStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getDesignStatus()), DemandRecord::getDesignStatus, bo.getDesignStatus());
        lqw.between(params.get("beginDesignUpdateTime") != null && params.get("endDesignUpdateTime") != null, DemandRecord::getDesignUpdateTime ,params.get("beginDesignUpdateTime"), params.get("endDesignUpdateTime"));
        lqw.like(StringUtils.isNotBlank(bo.getReleasePerson()), DemandRecord::getReleasePerson, bo.getReleasePerson());
        lqw.like(StringUtils.isNotBlank(bo.getReleaseSum()), DemandRecord::getReleaseSum, bo.getReleaseSum());
        List<String> releaseStatusArr = bo.getReleaseStatusArr();
        if (releaseStatusArr != null && releaseStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : releaseStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getReleaseStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getReleaseStatus()), DemandRecord::getReleaseStatus, bo.getReleaseStatus());
        lqw.between(params.get("beginReleaseUpdateTime") != null && params.get("endReleaseUpdateTime") != null, DemandRecord::getReleaseUpdateTime ,params.get("beginReleaseUpdateTime"), params.get("endReleaseUpdateTime"));
        lqw.like(StringUtils.isNotBlank(bo.getSaleSum()), DemandRecord::getSaleSum, bo.getSaleSum());
        if (AnalysisSelect != null && AnalysisSelect.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : AnalysisSelect) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getAnalysisSelect, label);
                    }
                }
            });
        }
        lqw.between(params.get("beginSaleUpdateTime") != null && params.get("endSaleUpdateTime") != null,
            DemandRecord::getSaleUpdateTime ,params.get("beginSaleUpdateTime"), params.get("endSaleUpdateTime"));
        List<String> nowStatusArr = bo.getNowStatusArr();
        if (nowStatusArr != null && nowStatusArr.size() > 0) {
            // 遍历数组构造 `like` 条件
            lqw.and(wrapper -> {
                for (String label : nowStatusArr) {
                    if (StringUtils.isNotBlank(label)) {
                        // 每个标签构造一个 `like` 条件，并用 `or` 连接
                        wrapper.or().like(DemandRecord::getNowStatus, label);
                    }
                }
            });
        }
        lqw.eq(StringUtils.isNotBlank(bo.getNowStatus()), DemandRecord::getNowStatus, bo.getNowStatus());
        lqw.orderByDesc(DemandRecord::getCreateTime);
        return lqw;
    }

    /**
     * 新增demand
     */
    @Override
    public Boolean insertByBo(DemandRecordBo bo) {
        DemandRecord add = BeanCopyUtils.copy(bo, DemandRecord.class);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            add.setNowStatus("1");
            if("1".equals(bo.getFilterStatus())||"2".equals(bo.getFilterStatus())||"3".equals(bo.getFilterStatus())||"4".equals(bo.getFilterStatus())){
            add.setNowStatus("2");
                add.setFilterUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                if("1".equals(bo.getSurveyStatus())){
                    add.setNowStatus("3");
                    add.setSurveyUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                    if("1".equals(bo.getAnalysisStatus())){
                        add.setNowStatus("4");
                        add.setAnalysisUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                        if("1".equals(bo.getReviewStatus())){
                            add.setNowStatus("5");
                            add.setReviewUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                            if("1".equals(bo.getDesignStatus())){
                                add.setNowStatus("6");
                                add.setDesignUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                                if("1".equals(bo.getDevelopStatus())){
                                    add.setNowStatus("7");
                                    add.setDevelopUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                                    if("1".equals(bo.getReleaseStatus())){
                                        add.setNowStatus("8");
                                        add.setReleaseUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                                        if(bo.getProductLabel()!=null){
                                            add.setSaleUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        add.setCreateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        boolean finalFlag =false;
        if(flag){
            finalFlag =baseMapper.updateDemandId(add.getId())>0;

        }
        return finalFlag;
    }


    /**
     * 修改demand
     */
    @Override
    public Boolean updateByBo(DemandRecordBo bo) {
        DemandRecord update = BeanCopyUtils.copy(bo, DemandRecord.class);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 当前状态（0enter, 1filter,2survey,3analysis,4.review，5design,6develop,7release,8上市）
            update.setNowStatus("1");
        if("1".equals(bo.getFilterStatus())||"2".equals(bo.getFilterStatus())||"3".equals(bo.getFilterStatus())||"4".equals(bo.getFilterStatus())){
            update.setNowStatus("2");
            update.setFilterUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
            if("1".equals(bo.getSurveyStatus())){
                update.setNowStatus("3");
                update.setSurveyUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                if("1".equals(bo.getAnalysisStatus())){
                    update.setNowStatus("4");
                    update.setAnalysisUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                    if("1".equals(bo.getReviewStatus())){
                        update.setNowStatus("5");
                        update.setReviewUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                        if("1".equals(bo.getDesignStatus())){
                            update.setNowStatus("6");
                            update.setDesignUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                            if("1".equals(bo.getDevelopStatus())){
                                update.setNowStatus("7");
                                update.setDevelopUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                                if("1".equals(bo.getReleaseStatus())){
                                    update.setNowStatus("8");
                                    update.setReleaseUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                                    if(bo.getProductLabel()!=null){
                                        update.setSaleUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        update.setUpdateTime(LocalDateTime.parse(DateUtils.getTime(), formatter));
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DemandRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除demand
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<DemandRecordVo> vos =baseMapper.selectVoBatchIds(ids);
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean deleteById(Long id) {
        DemandRecord update =baseMapper.selectById(id);
        return baseMapper.deleteById(update) > 0;
    }

    @Override
    public UserParam username(HttpServletRequest request) {
        String authorizationHeader = request.getHeader("Authortoken");
        String loginUser = jwtUtil.extractUsername(authorizationHeader);
        Object o = remoteSsoService.getUserInfo(APPID, loginUser);
        UserParam userParam = new UserParam();
        if (o instanceof Map) {
            Map<String, Object> resultMap = (Map<String, Object>) o;
            if ((int) resultMap.get("code") == 200) {
                Map<String, Object> userInfoMap = (Map<String, Object>) resultMap.get("data");
                userParam.setUserid((String) userInfoMap.get("userid"));
                userParam.setUsername((String) userInfoMap.get("username"));
            }
        }
        return userParam;
    }

    @Override
    public Boolean updateVersion(String ids) {
        CommonResult<List<Map<String, Object>>> list = iFeedbackApplicationVersionManagerDetailService.listDetail(ids);
        String[] split = ids.split(",");
        // 获取 CommonResult 中的 data 列表
        List<Map<String, Object>> dataList = list.getData();
        // 检查 split 和 dataList 长度是否一致
        if (split.length != dataList.size()) {
            throw new IllegalArgumentException("IDs 与返回数据的数量不匹配");
        }
        boolean boo =false;
        // 遍历每个元素（通过索引）
        for (int i = 0; i < dataList.size(); i++) {
            Map<String, Object> item = dataList.get(i);
            String splitId = split[i]; // 当前对应的 ID
            // 提取字段（假设字段是 List<String>）
            List<String> productModelIds = (List<String>) item.get("productmodelids");
            List<String> modelVersions = (List<String>) item.get("modelversions");
            List<String> appVersions = (List<String>) item.get("applicationversions");
            List<String> productTypeIds = (List<String>) item.get("producttypeids");
            List<String> appIds = (List<String>) item.get("applicationids");

            // 调用方法，将 splitId 作为参数传递（示例）
            DemandRecord demandRecord =baseMapper.selectById(splitId);
            DemandRecord update = BeanCopyUtils.copy(demandRecord, DemandRecord.class);
            update.setAppApply(appIds);
            update.setAppVersion(appVersions);
            update.setApplyVersion(combineLists(appIds,appVersions));
            update.setVersionCategory(productTypeIds);
            update.setVersionModel(productModelIds);
            update.setVersionModelVersion(modelVersions);
            update.setCategoryModelVersion(combineLists(productTypeIds,productModelIds,modelVersions));
            boo = baseMapper.updateById(update) > 0;
        }
        return boo;
    }
    // 函数：将多个List拼接成二维List
    public static List<List<String>> combineLists(List<String>... lists) {
        // 结果列表
        List<List<String>> result = new ArrayList<>();

        // 获取每个List的长度（假设每个List长度相同）
        int length = lists[0].size();

        // 遍历每个位置，组合成新的子列表
        for (int i = 0; i < length; i++) {
            List<String> combined = new ArrayList<>();
            for (List<String> list : lists) {
                combined.add(list.get(i)); // 获取每个List中第i个元素
            }
            result.add(combined); // 将组合好的列表加入到结果列表中
        }

        return result;
    }
}
